<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>SSE 实时消息推送示例</title>
</head>
<body>
    <div>
        接收消息
    </div>
</body>
<script>
    // 服务地址
    const host = "http://localhost:8080";
    // 用时间戳模拟登录用户
    const userId = 3;

    if (window.EventSource) {
        // 创建 EventSource 对象连接后端
        var source = new EventSource(host + '/sse/connect/' + userId);

        // 处理接收到的消息
        source.onmessage = function (event) {
          console.log(event.data);
          var div = document.createElement('div');
          div.innerHTML = event.data;
          document.body.appendChild(div);
        };

        // 处理连接错误
        source.onerror = function (error) {
          console.error('SSE 连接错误:', error);
        };
    } else {
        setMessageInnerHTML("你的浏览器不支持SSE");
    }
    // 监听窗口关闭事件，主动去关闭sse连接，如果服务端设置永不过期，浏览器关闭后手动清理服务端数据
    window.onbeforeunload = function () {
        closeSse();
    };

    // 关闭Sse连接
    function closeSse() {
        source.close();
        const httpRequest = new XMLHttpRequest();
        httpRequest.open('GET', host + '/sse/close/' + userId, true);
        httpRequest.send();
        console.log("close");
    }

</script>
</html>